#import "TracDataManager.h"
#import "TimeTrackerAppDelegate.h"
#import "CoreGraphics/CoreGraphics.h"
#import "XMLRPCResponse.h"
#import "XMLRPCRequest.h"
#import "XMLRPCConnection.h"

@interface TracDataManager (private)

- (void) loadTaskData;
- (void) setTaskList:(NSMutableArray *)newArray;

// set methods will release current and create mutable copy
- (void) setCurrentTask:(Task *)aTask;

@end

@implementation TracDataManager

static TracDataManager *sharedTracDataManager;

@synthesize currentTask, userTasks, userTasksByName,currentTaskIndex;


- (void)dealloc {
	
	[userTasks release];
	[currentTask release];
	[userTasksByName release];
	[super dealloc];
}


// Initialize the singleton instance if needed and return
+(TracDataManager *)sharedTracDataManager
{
//	@synchronized(self)
	{
		if (!sharedTracDataManager)
			sharedTracDataManager = [[TracDataManager alloc] init];
		
		return sharedTracDataManager;
	}
}

+(id)alloc {
//	@synchronized(self)
	{
		NSAssert(sharedTracDataManager == nil, @"Attempted to allocate a second instance of a singleton.");
		sharedTracDataManager = [super alloc];
		return sharedTracDataManager;
	}
}

+ (void)initialize {
    static BOOL initialized = NO;
	//int isRunning = 0;
    if (!initialized) {
		/*NSString *stringURL = [[NSString alloc] initWithString: @"my-trac.assembla.com/bd-time-tracker/login/xmlrpc"];

		//NSString *formattedString = [NSString stringWithFormat:@"http://%@", stringURL];
		isRunning = (int)[[TracDataManager sharedTracDataManager] checkXMLRPCTracIsRunning:stringURL];
		[stringURL release];
		//[[TracDataManager sharedTracDataManager] loadTaskData];
		if (isRunning != 0) {
			 initialized = YES;
		}else {
			initialized = NO;
		}*/
    }
}

- (id)init {
	if( self = [super init] ){
		
	}
	return self;
}


// loads blogs for each host that has been defined
-(void)loadTaskData {
	
}


- (void)setTaskList:(NSMutableArray *)newArray {

}

- (void) setCurrentTask:(Task *)aTask {
	
	if (currentTask!= aTask)
    {
        [currentTask release];
        currentTask = [aTask retain];
    }
}

#pragma mark - XMLRPC


- (NSError *)defaultError {
	NSDictionary *usrInfo = [NSDictionary dictionaryWithObjectsAndKeys:@"Failed to request the server.", NSLocalizedDescriptionKey, nil];
	return [NSError errorWithDomain:@"com.effigent.iphone.wordpress" code:-1 userInfo:usrInfo];
}

- (BOOL)handleError:(NSError *)err
{
	UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"Communication Error"
													message:[err localizedDescription]
													delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	
	[alert1 show];
	//TimeTrackerAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	//[delegate setAlertRunning:YES];

	
	[alert1 release];
	return YES;
}

- (NSError *)errorWithResponse:(XMLRPCResponse *)res shouldHandle:(BOOL)shouldHandleFlag {
	NSError *err = nil;
	if( !res )
		err = [self defaultError];

	if ( [res isKindOfClass:[NSError class]] )
		err = (NSError *)res;
	else
	{
		if ( [res isFault] )
		{
			NSDictionary *usrInfo = [NSDictionary dictionaryWithObjectsAndKeys:[res fault], NSLocalizedDescriptionKey, nil];
			err = [NSError errorWithDomain:@"my-trac.assembla.com" code:[[res code] intValue] userInfo:usrInfo];
		}
		
		if ( [res isParseError] )
		{
			err = [res object];
		}		
	}
	
	if( err && shouldHandleFlag )
	{
		// patch to eat the zero posts error
		// "Either there are no posts, or something went wrong."
		
		NSString *zeroPostsError = @"Either there are no posts, or something went wrong.";
		NSRange range = [[err description] rangeOfString:zeroPostsError options:NSBackwardsSearch];
		if (range.location == NSNotFound) {
			[self handleError:err]; 
		} else {
			return [NSMutableArray array];
		}
	}
	
	return err;
}

- (id)executeXMLRPCRequest:(XMLRPCRequest *)req byHandlingError:(BOOL)shouldHandleFalg {
	XMLRPCResponse *userInfoResponse = [XMLRPCConnection sendSynchronousXMLRPCRequest:req];
	NSError *err = [self errorWithResponse:userInfoResponse shouldHandle:shouldHandleFalg];

	if( err )
		return err;
	
	return [userInfoResponse object];
}

#pragma mark -

- (void)syncTasksForUser:(id)userID{
	
}

/*
- (NSString *)pagePictureURLForPicturePathBySendingToServer:(NSString *)filePath
{
	//	UIImage *pict = [UIImage imageWithContentsOfFile:filePath];
	//UIImagePNGRepresentation(pict);s
	NSData *pictData = [NSData dataWithContentsOfFile:filePath];
	if( pictData == nil )
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
														message:@"Invalid Image. Unable to Upload to the server." 
													   delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		
		[alert show];
		WordPressAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
		[delegate setAlertRunning:YES];

		return nil;
	}
	
	NSMutableDictionary *imageParms = [NSMutableDictionary dictionary];
	[imageParms setValue:@"image/jpeg" forKey:@"type"];
	[imageParms setValue:pictData forKey:@"bits"];
	[imageParms setValue:[filePath lastPathComponent] forKey:@"name"];
	//	[imageParms setValue:categories forKey:@"categories"];
	//	[imageParms setValue:desc forKey:@"description"];
	
	//id blog = [self blogForId:[currentPost valueForKey:@"blogid"] hostName:[currentPost valueForKey:@"blog_host_name"]];
	id blog = [self blogForId:[currentPage valueForKey:@"blogid"] hostName:[currentPage valueForKey:@"blog_host_name"]];
	
	
	
	NSArray *args = [NSArray arrayWithObjects:[blog valueForKey:@"blogid"],
					 [blog valueForKey:@"username"],
					 [blog valueForKey:@"pwd"],
					 imageParms,
					 nil
					 ];
	
	XMLRPCRequest *request = [[XMLRPCRequest alloc] initWithHost:[NSURL URLWithString:[blog valueForKey:@"xmlrpc"]]];
	[request setMethod:@"metaWeblog.newMediaObject" withObjects:args];
	
	id response = [self executeXMLRPCRequest:request byHandlingError:YES];
	[request release];
	if( [response isKindOfClass:[NSError class]] )
	{
		return nil;
	}
	else
	{
		return [response valueForKey:@"url"];
	}
	
	return nil;
}*/

- (NSDictionary *)userTasksByName {
	return nil;
}

- (NSString *)xmlurl:(NSString *)hosturl {
	//Handeled if HostUrl is nil from server.
	if(!hosturl)
		return nil;
	
	NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:hosturl]
											  cachePolicy:NSURLRequestUseProtocolCachePolicy							  
										  timeoutInterval:60.0];			
	NSData *data = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:NULL error:NULL];
	
	// NSString *xmlstr = [NSString stringWithUTF8String:[data bytes]];
	NSString *xmlstr = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
	
	if( [data length] > 0 ){
		NSRange range1 = [xmlstr rangeOfString:@"preferred=\"true\""];
		if (range1.location != NSNotFound) {
			NSRange lr1 = NSMakeRange(range1.location, [xmlstr length]-range1.location);
			NSRange endRange1 = [xmlstr rangeOfString:@"/>" options:NSLiteralSearch range:lr1];
			if (endRange1.location != NSNotFound) {
				NSString *ourStr = [xmlstr substringWithRange:NSMakeRange(range1.location, endRange1.location-range1.location)];
				
				ourStr = [ourStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
				ourStr = [ourStr substringWithRange:NSMakeRange(0, [ourStr length]-1)];
				NSRange r1 = [ourStr rangeOfString:@"\"" options:NSBackwardsSearch];
				if (r1.location != NSNotFound) {
					NSString *xmlrpcurl = [ourStr substringWithRange:NSMakeRange(r1.location+1, [ourStr length]-r1.location-1)];			
					return xmlrpcurl;
				}
			}
		}
	}
	return nil;
}

- (int)checkXMLRPCTracIsRunning:(NSString *)xmlrpcurl {
	
	XMLRPCRequest *listMethodsReq = [[XMLRPCRequest alloc] initWithHost:[NSURL URLWithString:xmlrpcurl]];
	listMethodsReq.method = @"system.listMethods";
	NSArray *listOfMethods = [self executeXMLRPCRequest:listMethodsReq byHandlingError:YES];
	[listMethodsReq release];
	
	if( [listOfMethods isKindOfClass:[NSError class]] )
		return -1;

	if ( [listOfMethods containsObject:@"ticket.query"] ){
		return 1;
	}else {
		return 0;
	}
}

- (void)saveTaskData {
	
	
}

- (Task *)taskAtIndex:(NSUInteger)theIndex {
	
	return [userTasks objectAtIndex:theIndex];

}

- (BOOL)doesTaskExists:(Task *)aTask {
	return false;
}

- (NSArray *)tasksForUser:(NSString *)xmlrpcurl:(NSString *)username{
	NSString *owner = @"owner=";
	NSArray *args = [NSArray arrayWithObjects:[owner stringByAppendingString:username],nil];
	
	XMLRPCRequest *listTasksReq = [[XMLRPCRequest alloc] initWithHost:[NSURL URLWithString:xmlrpcurl]];
	[listTasksReq setMethod:@"ticket.query" withObjects:args];
	NSArray *listOfTasks = [self executeXMLRPCRequest:listTasksReq byHandlingError:YES];
	[listTasksReq release];
	return listOfTasks;
}

- (NSInteger)indexForTaskid:(NSString *)taskId  hostName:(NSString *)hostname {
	
	return	0;	
}

- (BOOL)saveTask:(Task *)aTask {
	return false;
}

- (void)makeTaskAtIndexCurrent:(NSUInteger)theIndex {
	
}

- (void)makeNewTaskCurrent {
	
}

-(void)saveCurrentTask{	
	
}
- (void)resetCurrentTask {

}

- (void)removeCurrentTask{

}
@end
